package com.quanta.edaily.controller;

import com.quanta.edaily.Service.GlobalsService;
import com.quanta.edaily.bean.JsonResponse;
import com.quanta.edaily.bean.contants.ResultCode;
import com.quanta.edaily.pojo.Globals;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Min;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/globals")
@Validated
public class GlobalsController {
    @Resource
    GlobalsService globalsService;

    @PostMapping("/insert")
    public JsonResponse insert(@RequestBody Globals globals) {
        if (globalsService.insert(globals) == 1) return JsonResponse.success("插入成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "插入失败");
    }

    @PostMapping("/deleteById/{id}")
    public JsonResponse deleteById(@PathVariable Integer id) {
        if (globalsService.deleteById(id) == 1) return JsonResponse.success("删除成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "删除失败");
    }

    @PostMapping("/updateById")
    public JsonResponse updateById(@RequestBody Globals globals) {
        if (globalsService.updateById(globals) == 1) return JsonResponse.success("更改成功");
        else return JsonResponse.error(ResultCode.SERVICE_ERROR, "更改失败");
    }

    @GetMapping("/getById/{id}")
    public JsonResponse getById(@PathVariable Integer id) {
        Globals globals = globalsService.getById(id);
        if(globals ==null)
            return JsonResponse.paramError("查询失败");
        globals.setReadCount(globals.getReadCount()==null?0:globals.getReadCount()+1);
        globalsService.updateById(globals);
        return JsonResponse.success("查询成功", globals);
    }

    @GetMapping("/getSome")
    public JsonResponse findPage(@Nullable @RequestParam @Min(1) Integer pageNum,
                                 @Nullable @RequestParam @Min(1) Integer pageSize,
                                 @Nullable @RequestParam String title) {
        if(pageNum==null&&pageSize==null)
            return JsonResponse.success("查询成功", globalsService.getSome(null, null, title));
        if(pageNum!=null&&pageSize!=null)
            return JsonResponse.success("查询成功", globalsService.getSome((pageNum-1)*pageSize, pageSize, title));
        return JsonResponse.paramError("参数错误");
    }
}
